package com.cw.lang.common.framework.converter;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import com.cw.base.common.model.dto.base.BaseUserReqDto;
import com.cw.lang.common.constants.SymbolConstants;
import com.cw.lang.common.exception.BizException;
import com.cw.lang.common.framework.enums.EnumRpcError;
import com.cw.lang.common.utils.StringUtil;
import com.google.common.base.Splitter;

/**
 * @author chenw
 * @version $$Id: BaseRequestConverter.java, v 0.1 2018/11/1 5:01 PM chenw Exp $$
 */
public class BaseUserRequestConverter {
    /** 通行证ID */
    private static final String AUTH_ID = "authId";
    /** 签名-渠道端的用户认证ID */
    private static final String TOKEN = "token";
    /** 操作人id */
    private static final String OPERATOR_ID = "operatorId";
    /** 操作人名称 */
    private static final String OPERATOR_NAME = "operatorName";
    /** 所属组织id */
    private static final String ORGAN_ID = "organId";
    /** 所属组织名称 */
    private static final String ORGAN_NAME = "organName";

    /**
     * 把对象转为uri结构
     *
     * @param baseUserReqDto {@link BaseUserReqDto}
     * @return uri结构字符串
     */
    public static String encode(BaseUserReqDto baseUserReqDto) {
        if (baseUserReqDto == null) {
            return StringUtil.EMPTY;
        }
        StringBuilder sb = new StringBuilder();
        if (StringUtil.isNotBlank(baseUserReqDto.getAuthId())) {
            sb.append(AUTH_ID)
                .append(SymbolConstants.EQUAL)
                .append(baseUserReqDto.getAuthId())
                .append(SymbolConstants.AND);
        }
        if (StringUtil.isNotBlank(baseUserReqDto.getToken())) {
            sb.append(TOKEN)
                .append(SymbolConstants.EQUAL)
                .append(baseUserReqDto.getToken())
                .append(SymbolConstants.AND);
        }
        if (StringUtil.isNotBlank(baseUserReqDto.getOperatorId())) {
            sb.append(OPERATOR_ID)
                .append(SymbolConstants.EQUAL)
                .append(baseUserReqDto.getOperatorId())
                .append(SymbolConstants.AND);
        }
        if (StringUtil.isNotBlank(baseUserReqDto.getOperatorName())) {
            sb.append(OPERATOR_NAME)
                .append(SymbolConstants.EQUAL)
                .append(urlEncode(baseUserReqDto.getOperatorName()))
                .append(SymbolConstants.AND);
        }
        if (StringUtil.isNotBlank(baseUserReqDto.getOrganId())) {
            sb.append(ORGAN_ID)
                .append(SymbolConstants.EQUAL)
                .append(baseUserReqDto.getOrganId())
                .append(SymbolConstants.AND);
        }
        if (StringUtil.isNotBlank(baseUserReqDto.getOperatorName())) {
            sb.append(ORGAN_NAME)
                .append(SymbolConstants.EQUAL)
                .append(urlEncode(baseUserReqDto.getOrganName()))
                .append(SymbolConstants.AND);
        }
        return sb.length() == 0 ? StringUtil.EMPTY : sb.substring(0, sb.length() - 1);
    }

    /**
     * 把uri结构字符串转为对象
     *
     * @param uriStr uri结构字符串
     * @return {@link BaseUserReqDto}
     */
    public static BaseUserReqDto decode(String uriStr) {
        if (StringUtil.isBlank(uriStr)) {
            return null;
        }
        BaseUserReqDto.Builder builder = BaseUserReqDto.Builder.getInstance();
        List<String> parameterList = Splitter.on(SymbolConstants.AND)
            .splitToList(uriStr);
        for (String parameter : parameterList) {
            List<String> nameValueParameter = Splitter.on(SymbolConstants.EQUAL)
                .splitToList(parameter);
            if (AUTH_ID.equals(nameValueParameter.get(0))) {
                builder.addAuthId(nameValueParameter.get(1));
            }
            if (TOKEN.equals(nameValueParameter.get(0))) {
                builder.addToken(nameValueParameter.get(1));
            }
            if (OPERATOR_ID.equals(nameValueParameter.get(0))) {
                builder.addOperatorId(nameValueParameter.get(1));
            }
            if (OPERATOR_NAME.equals(nameValueParameter.get(0))) {
                builder.addOperatorName(urlDecode(nameValueParameter.get(1)));
            }
            if (ORGAN_ID.equals(nameValueParameter.get(0))) {
                builder.addOrganId(nameValueParameter.get(1));
            }
            if (ORGAN_NAME.equals(nameValueParameter.get(0))) {
                builder.addOrganName(urlDecode(nameValueParameter.get(1)));
            }
        }
        return builder.build();
    }

    /**
     * 解码
     *
     * @param uri 编码参数
     * @return 解码参数
     */
    private static String urlDecode(String uri) {

        if (StringUtil.isBlank(uri)) {
            return null;
        }

        try {
            return URLDecoder.decode(uri, StandardCharsets.UTF_8.displayName());
        } catch (UnsupportedEncodingException e) {
            throw new BizException(EnumRpcError.HEADER_PARAM_CODEC_ERR.getCode(),
                EnumRpcError.HEADER_PARAM_CODEC_ERR.getDescription());
        }
    }

    /**
     * 编码
     *
     * @param uri 参数
     * @return 编码参数
     */
    private static String urlEncode(String uri) {

        if (StringUtil.isBlank(uri)) {
            return null;
        }

        try {
            return URLEncoder.encode(uri, StandardCharsets.UTF_8.displayName());
        } catch (UnsupportedEncodingException e) {
            throw new BizException(EnumRpcError.HEADER_PARAM_CODEC_ERR.getCode(),
                EnumRpcError.HEADER_PARAM_CODEC_ERR.getDescription());
        }
    }
}
